//
//  CYCheliangVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/13.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYCheliangVC.h"
#import "LEUnitView+LE.h"
#import "CYCreditTool.h"
#import "CustomIOSAlertView.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "LEPhotoBrowserTool.h"
#import "CYLoginHttpTool.h"
#import "CYUser.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "LEImagePickerTool.h"
#import "MBProgressHUD+LE.h"
#import "CYDiscoveryHttpTool.h"
#import "UIButton+WebCache.h"

@interface CYCheliangVC ()
@property (weak, nonatomic) IBOutlet UIView *zmSubmitView;
@property (weak, nonatomic) IBOutlet UIView *fmSubmitView;
@property (weak, nonatomic) IBOutlet UIView *heyingSubmitView;

@property (weak, nonatomic) IBOutlet UILabel *baipaiLab;
@property (weak, nonatomic) IBOutlet UILabel *shouchiLab;
@property (weak, nonatomic) IBOutlet UILabel *heyingLab;

@property (nonatomic, strong) NSMutableArray *baipaisubmitUrl;
@property (nonatomic, strong) NSMutableArray *shouchisubmitUrl;
@property (nonatomic, strong) NSMutableArray *heyingsubmitUrl;
@property (nonatomic, strong) NSArray *baipaiArr;
@property (nonatomic, strong) NSArray *shouchiArr;
@property (nonatomic, strong) NSArray *heyingArr;
@property (nonatomic, strong) NSMutableDictionary *cheliangDic;
@property (weak, nonatomic) IBOutlet UIView *cheliangrecordView;
@property (weak, nonatomic) IBOutlet UILabel *cheliangrecordLab;
@property (nonatomic, strong) NSMutableArray *recordimageUrls;
@property (weak, nonatomic) IBOutlet UIButton *baipai1;
@property (weak, nonatomic) IBOutlet UIButton *baipai2;
@property (weak, nonatomic) IBOutlet UIButton *shouchi1;
@property (weak, nonatomic) IBOutlet UIButton *shouchi2;
@property (weak, nonatomic) IBOutlet UIButton *heying1;


@end

@implementation CYCheliangVC

- (void)viewDidLoad {
     [super viewDidLoad];
     self.title = @"车辆";
     
     [_baipai1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/1.png"] forState:UIControlStateNormal];
     [_baipai2 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/3.png"] forState:UIControlStateNormal];
     [_shouchi1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/4.png"] forState:UIControlStateNormal];
      [_shouchi2 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/5.png"] forState:UIControlStateNormal];
      [_heying1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/6.png"] forState:UIControlStateNormal];
     
     _baipaisubmitUrl = [[NSMutableArray alloc]init];
     _shouchisubmitUrl = [[NSMutableArray alloc]init];
     _heyingsubmitUrl = [[NSMutableArray alloc]init];
     _cheliangDic = [[NSMutableDictionary alloc]init];
     _recordimageUrls = [[NSMutableArray alloc]init];
     
     
     NSDictionary *cheliangdic = [[NSDictionary alloc] initWithContentsOfFile:@"cheliangImage.plist"];
     _baipaiArr = [cheliangdic objectForKey:@"baipaiUrl"];
     _shouchiArr = [cheliangdic objectForKey:@"shouchiUrl"];
     _heyingArr = [cheliangdic objectForKey:@"heyingUrl"];
     
     if (_baipaiArr.count) {
          _baipaiLab.text = @"已上传，再次上传将会重新更新此类";
          _baipaiLab.textColor = [UIColor redColor];
     }
     if (_shouchiArr.count) {
          _shouchiLab.text = @"已上传，再次上传将会重新更新此类";
          _shouchiLab.textColor = [UIColor redColor];
     }
     if (_heyingArr.count) {
          _heyingLab.text = @"已上传，再次上传将会重新更新此类";
          _heyingLab.textColor = [UIColor redColor];
     }
     
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(submitclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"确定" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;

     
     
     [self setupUploadView];
     [self setimagerecordView];
    // Do any additional setup after loading the view from its nib.
}

-(void)setimagerecordView{
     // image 后缀
     NSString *preFixString = @"http://image.credit-manage.com/";
     // 屏幕的宽度 (也是承载imageView的view的宽度)
     CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
     // image各个边界的间隔
     CGFloat space = 10.f;
     // imageview的width (设定为5张)
     CGFloat imgWidth = (screenWidth - space * 6 ) / 5;
     // imageview的height
     CGFloat imgHeight = _cheliangrecordView.frame.size.height - space * 2;
     // 由于是xib + 手码, 代码获取xib控件的frame 必须在主线程中获取
     dispatch_async(dispatch_get_main_queue(), ^{
          CYUser *user = [CYLoginHttpTool userData].user;
          [CYHttpTool postWithURL:[CYURL shared].getAssetInfoPics params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
               //        CYLog(@"json = %@",json);
               CYJsonInfo *jsoninf = [CYJsonInfo objectWithKeyValues:json];
               NSMutableArray *data = jsoninf.data;
               for (NSDictionary *dic in data) {
                    // 取网络图片地址
                    NSString *assetPicAddress = [dic objectForKey:@"assetPicAddress"];
                    //取type
                    NSInteger type = [[dic objectForKey:@"type"] integerValue];
                    switch (type) {
                         case 2:
                              [_recordimageUrls addObject:assetPicAddress];
                              break;
                    }
               }
               for (int i = 0; i < _recordimageUrls.count; i++ ) {
                    // image的url string
                    NSString *imgUrlString = [_recordimageUrls objectAtIndex:i];
                    imgUrlString = [preFixString stringByAppendingString:imgUrlString];
                    // 创建imageView
                    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(space + (imgWidth + space) * i, space, imgWidth, imgHeight)];
                    imgView.backgroundColor = [UIColor whiteColor];
                    // 此处你可使用SDWebImage来加载
                    [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrlString]];
                    [_cheliangrecordView addSubview:imgView];
               }
               if (_recordimageUrls.count) {
                    _cheliangrecordLab.hidden = YES;
                    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoBrowser:)];
                    [_cheliangrecordView addGestureRecognizer:tag];
               }
               
               
          } failure:^(NSError *error) {
               
          }];
     });
     
     
}

/**
 *  图片浏览器
 */
- (void)photoBrowser:(UITapGestureRecognizer *)tag {
     NSArray *urls = _recordimageUrls;
     MWPhoto *photo = nil;
     NSMutableArray *photos = [NSMutableArray array];
     for (NSString *url in urls) {
          photo = [MWPhoto photoWithURL:CYURLWithService(url)];
          //        photo.caption = @"title";
          [photos addObject:photo];
     }
     [LEPhotoBrowserTool showPhotoBrowserWithController:self photos:photos];
}



-(void)submitclick{
     
     [_cheliangDic removeAllObjects];
     if (_baipaisubmitUrl.count) {
          [_cheliangDic setObject:_baipaisubmitUrl forKey:@"baipaiUrl"];
          
     }else if (!_baipaisubmitUrl.count && _baipaiArr.count) {
          [_cheliangDic setObject:_baipaiArr forKey:@"baipaiUrl"];
          
     }
     if (_shouchisubmitUrl.count) {
          [_cheliangDic setObject:_shouchisubmitUrl forKey:@"shouchiUrl"];
          
     }else if (!_shouchisubmitUrl.count && _shouchiArr.count) {
          [_cheliangDic setObject:_shouchiArr forKey:@"shouchiUrl"];
          
     }
     if (_heyingsubmitUrl.count) {
          [_cheliangDic setObject:_heyingsubmitUrl forKey:@"heyingUrl"];
          
     }else if (!_heyingsubmitUrl.count && _heyingArr.count) {
          [_cheliangDic setObject:_heyingArr forKey:@"heyingUrl"];
          
     }
     
     if (_baipaiArr.count !=0 && _shouchiArr !=0 && _heyingArr != 0) {
          
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *plistPath1= [paths objectAtIndex:0];
          NSLog(@"%@",plistPath1);
          //得到完整的路径名
          NSString *fileName = [plistPath1 stringByAppendingPathComponent:@"cheliangImage.plist"];
          //NSMutableDictionary *myDic = [[NSMutableDictionary alloc]init];
          //[myDic setValuesForKeysWithDictionary:cityDic];
          NSFileManager *fm = [NSFileManager defaultManager];
          
          if ([fm createFileAtPath:fileName contents:nil attributes:nil] ==YES) {
               [_cheliangDic writeToFile:fileName atomically:YES];
               NSLog(@"文件写入完成");
               CYLog(@"cheliangdic = %@",_cheliangDic);
               [[NSNotificationCenter defaultCenter] postNotificationName:@"CYNewAssetNotification" object:nil userInfo:nil];
               [self.navigationController popViewControllerAnimated:YES];
               
          }
          return;
     }
     
     if (_baipaisubmitUrl.count != 0 && _shouchisubmitUrl.count != 0 && _heyingsubmitUrl.count != 0 ) {
     
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *plistPath1= [paths objectAtIndex:0];
          NSLog(@"%@",plistPath1);
          //得到完整的路径名
          NSString *fileName = [plistPath1 stringByAppendingPathComponent:@"cheliangImage.plist"];
          //NSMutableDictionary *myDic = [[NSMutableDictionary alloc]init];
          //[myDic setValuesForKeysWithDictionary:cityDic];
          NSFileManager *fm = [NSFileManager defaultManager];
          
          if ([fm createFileAtPath:fileName contents:nil attributes:nil] ==YES) {
               [_cheliangDic writeToFile:fileName atomically:YES];
               NSLog(@"文件写入完成");
               CYLog(@"cheliangdic = %@",_cheliangDic);
               [[NSNotificationCenter defaultCenter] postNotificationName:@"CYNewAssetNotification" object:nil userInfo:nil];
               [self.navigationController popViewControllerAnimated:YES];
               
          }
          
     }else{
          CYAlertView(@"请按照要求提交！");
          
     }

     
     
}

- (void)setupUploadView {
     //正面
     [LEUnitView imageScrollView:self.zmSubmitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
          [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
          [_baipaisubmitUrl addObject:imageUrl];
               cell.ratio = 1;
          } failure:^(NSError *error) {
               //删除
               [unitView deleteLastCell];
          } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
               CGFloat a = totalBytesWritten;
               CGFloat b = totalBytesExpectedToWrite;
               cell.ratio = a/b - .01;
          }];
     } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
     }];

     //手持
     [LEUnitView imageScrollView:self.fmSubmitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
          [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
          [_shouchisubmitUrl addObject:imageUrl];
               cell.ratio = 1;
          } failure:^(NSError *error) {
               //删除
               [unitView deleteLastCell];
          } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
               CGFloat a = totalBytesWritten;
               CGFloat b = totalBytesExpectedToWrite;
               cell.ratio = a/b - .01;
          }];
     } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
     }];

     //合影
     [LEUnitView imageScrollView:self.heyingSubmitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
          [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
          [_heyingsubmitUrl addObject:imageUrl];
               cell.ratio = 1;
          } failure:^(NSError *error) {
               //删除
               [unitView deleteLastCell];
          } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
               CGFloat a = totalBytesWritten;
               CGFloat b = totalBytesExpectedToWrite;
               cell.ratio = a/b - .01;
          }];
     } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
     }];
}

- (IBAction)zm1:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/1.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}
- (IBAction)zm2:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/3.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}
- (IBAction)zm3:(id)sender {
}

- (IBAction)shouchi1:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/4.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}
- (IBAction)shouchi2:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/5.png"]];     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}
- (IBAction)shouchi3:(id)sender {
}
- (IBAction)shouchi4:(id)sender {
}
- (IBAction)heying1:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/cheliang/6.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];
}
- (IBAction)heying2:(id)sender {
}
- (IBAction)heying3:(id)sender {
}
- (IBAction)heying4:(id)sender {
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
